//
//  KeepAddressVC.m
//  zhiche--delivery
//
//  Created by 王亚陆 on 16/7/18.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "KeepAddressVC.h"
#import <Masonry.h>
#import "Header.h"
#import "Common.h"
#import "ActionSheetPicker.h"
#import "area.h"
#import "PlaceOrderVC.h"
#import "ChooseAddressVC.h"
#import "WKProgressHUD.h"
#import <AMapSearchKit/AMapSearchKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>

#define AreaBtnTag 100
#define KeepBtnTag 200
#define FieldTag 500
#define kMaxLength 20

#define MySetValue(dict, value) ((!dict[value] || [dict[value] isKindOfClass:[NSNull class]])?@"":dict[value])


@interface KeepAddressVC ()<AMapSearchDelegate>
{
    UIImageView * nav;
    Common * Com;
    area * AREA;
    NSMutableDictionary * dic;
    WKProgressHUD *hud;
    

}
@property (nonatomic,strong) UIView * backView;
@property (nonatomic,strong) UIButton * AreaBtn;
@property (nonatomic, strong) NSMutableArray *provienceArray;
@property (nonatomic, strong) NSArray *cityArray;
@property (nonatomic, strong) NSArray *areaArray;
@property (nonatomic,assign) BOOL store;
@property (nonatomic,strong) AMapSearchAPI * search;


@end

@implementation KeepAddressVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = GrayColor;
    _backView = [[UIView alloc]init];
    _backView.backgroundColor = WhiteColor;
    [self.view addSubview:_backView];
    
    Com = [[Common alloc]init];
    AREA = [[area alloc]init];
    dic=[[NSMutableDictionary alloc]init];
    
    if ([_addresstype isEqualToString:@"1"]) {
        [dic setObject:@"1" forKey:@"addresstype"]; //地址类型(0:发车地址，1:送达地址)
    }else if ([_addresstype isEqualToString:@"0"]){
        [dic setObject:@"0" forKey:@"addresstype"]; //地址类型(0:发车地址，1:送达地址)
    }
    if ([_navtitle isEqualToString:@"1"]) {
        nav = [self createNav:@"收车地址编辑"];
    }else if ([_navtitle isEqualToString:@"0"]){
        nav = [self createNav:@"发车地址编辑"];
    }else{
        if ([_addresstype isEqualToString:@"1"]) {
            nav = [self createNav:@"新增收车地址"];
        }else{
            nav = [self createNav:@"新增发车地址"];
        }
    }
    [self.view addSubview:nav];
    [_backView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.top.mas_equalTo(nav.mas_bottom).with.offset(0);
        make.size.mas_equalTo(CGSizeMake(Main_Width, 215*kHeight));
    }];
    
    
    [dic setObject:@"" forKey:@"provincecode"];//省编码
    [dic setObject:@"" forKey:@"provincename"]; //省名称
    [dic setObject:@"" forKey:@"citycode"];//市编码
    [dic setObject:@"" forKey:@"cityname"]; //市名称
    [dic setObject:@"" forKey:@"countycode"];//县编码
    [dic setObject:@"" forKey:@"countyname"]; //县名称
    [dic setObject:@"" forKey:@"contact"];//联系人
    [dic setObject:@"" forKey:@"phone"]; //联系电话
    [dic setObject:@"" forKey:@"unitname"];//单位名称
    [dic setObject:@"" forKey:@"address"];//详细地址
    [dic setObject:@"F" forKey:@"isdefault"];//是否默认(F:否，T:是)
    [dic setObject:@"" forKey:@"comment"];//备注
    [self createUI];
    
    
    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;
    
    AMapPOIKeywordsSearchRequest *request = [[AMapPOIKeywordsSearchRequest alloc] init];
    request.keywords            = @"北京大学";
    [self.search AMapPOIKeywordsSearch:request];
    

}

- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
    if (response.pois.count == 0)
    {
        return;
    }else{
        NSLog(@"%@",response.pois);
    }
    
    
    //解析response获取POI信息，具体解析见 Demo
}

-(void)viewWillAppear:(BOOL)animated{
    
    
    
}

-(void)createUI{
    NSArray * arrName = nil;
    NSArray * FieldName =nil;
    if ([_addresstype isEqualToString:@"0"]) {
        arrName = @[@"区域",
                    @"发车单位",
                    @"联系人",
                    @"手机号码",
                    @"详细地址"];
        FieldName = @[@"请输入发车单位",
                      @"请输入联系人",
                      @"请输入联系电话",
                      @"请输入详细地址",];
    }
    else{
        arrName = @[@"区域",
                    @"收车单位",
                    @"联系人",
                    @"手机号码",
                    @"详细地址"];
        FieldName = @[@"请输入收车单位",
                      @"请输入联系人",
                      @"请输入联系电话",
                      @"请输入详细地址"];
    }
    
    if (self.dataSouce[@"id"]) {
        FieldName = @[self.dataSouce[@"unitName"],self.dataSouce[@"contact"],self.dataSouce[@"phone"],self.dataSouce[@"address"]];
        [dic setObject:self.dataSouce[@"addressType"] forKey:@"addresstype"]; //地址类型(0:发车地址，1:送达地址)
        [dic setObject:self.dataSouce[@"contact"] forKey:@"contact"];//联系人
        [dic setObject:self.dataSouce[@"phone"] forKey:@"phone"]; //联系电话
        [dic setObject:self.dataSouce[@"unitName"] forKey:@"unitname"];//单位名称
        [dic setObject:self.dataSouce[@"address"] forKey:@"address"];//详细地址
        [dic setObject:@"F" forKey:@"isdefault"];//是否默认(F:否，T:是)
        [dic setObject:self.dataSouce[@"comment"] forKey:@"comment"];//备注
        
    }
    for (int i=0; i<arrName.count; i++) {
        UILabel * label = [self createUIlabel:arrName[i] andFont:FontOfSize14 andColor:fontGrayColor];
        [_backView addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_backView.mas_left).with.offset(18*kWidth);
            make.centerY.mas_equalTo(_backView.mas_top).with.offset(43*kHeight*i+21.5*kHeight);
        }];
        
        UIView * Hline =[[UIView alloc]init];
        Hline.backgroundColor = LineGrayColor;
        [_backView addSubview:Hline];
        [Hline mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_backView.mas_left);
            make.bottom.mas_equalTo(_backView.mas_top).with.offset(43*kWidth*(i+1));
            make.size.mas_equalTo(CGSizeMake(Main_Width, 0.5));
        }];
        if (i==0) {
            NSString * string = nil;
            if (self.dataSouce[@"id"]) {
                
                NSString *provinceName = [NSString stringWithFormat:@"%@",self.dataSouce[@"provinceName"]];
                NSString *cityName = [NSString stringWithFormat:@"%@",self.dataSouce[@"cityName"]];
                
                if ([provinceName isEqualToString:cityName]) {
                    string = [NSString stringWithFormat:@"%@",provinceName];
                }else{
                    string = [NSString stringWithFormat:@"%@%@",provinceName,cityName];
                }
            }else{
                string = @"选择地址";
            }
            _AreaBtn = [self createBtn:string andTag:AreaBtnTag];
            _AreaBtn.titleLabel.font = Font(FontOfSize14);
            [_AreaBtn addTarget:self action:@selector(pressBtnArea) forControlEvents:UIControlEventTouchUpInside];
            [_backView addSubview:_AreaBtn];
            [_AreaBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(_backView.mas_left).with.offset(105*kWidth);
                make.centerY.mas_equalTo(label.mas_centerY);
                make.size.mas_equalTo(CGSizeMake(Main_Width/2, 25*kHeight));
            }];
            
            UIImageView * RightImage =[[UIImageView alloc]init];
            RightImage.image = [UIImage imageNamed:@"common_list_arrows_more"];
            RightImage.tag = 1000;
            [_backView addSubview:RightImage];
            [RightImage mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.equalTo(_backView.mas_right).with.offset(-15*kWidth);
                make.centerY.mas_equalTo(_AreaBtn.mas_centerY);
                make.size.mas_equalTo(CGSizeMake(8*kWidth, 13*kHeight));
            }];
        }
        else{
            //500 501 502 503
            UITextField * field = [self createField:FieldName[i-1] andTag:FieldTag+i-1 andFont:FontOfSize14];
            [_backView addSubview:field];
            [field mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(_backView.mas_left).with.offset(105*kWidth);
                make.centerY.mas_equalTo(label.mas_centerY);
                make.size.mas_equalTo(CGSizeMake(Main_Width/2, 25*kHeight));
            }];
        }
    }
    
    UIButton * ConfirmBtn = [self createBtn:@"保存并使用" andTag:KeepBtnTag];
    ConfirmBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    ConfirmBtn.titleLabel.font = Font(FontOfSize17);
    [ConfirmBtn setTitleColor:WhiteColor forState:UIControlStateNormal];
    [ConfirmBtn addTarget:self action:@selector(pressStoreBtn) forControlEvents:UIControlEventTouchUpInside];
    ConfirmBtn.backgroundColor = YellowColor;
    ConfirmBtn.layer.cornerRadius = 5;
    //    ConfirmBtn.layer.borderWidth = 1;
    //    ConfirmBtn.layer.borderColor = RGBACOLOR(149, 149, 149, 1).CGColor;
    [self.view addSubview:ConfirmBtn];
    [ConfirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(293*kWidth, 40*kHeight));
        make.top.mas_equalTo(_backView.mas_bottom).with.offset(30*kHeight);
    }];
}
-(void)pressBtnArea{
    
    _provienceArray = nil;
    _cityArray = nil;
    _areaArray = nil;
    
    _provienceArray = [AREA selectAreaWithFArea:nil withTarea:nil withFarea:1];
    _cityArray = [AREA selectAreaWithFArea:@"北京市" withTarea:nil withFarea:2];
    //    _areaArray = [AREA selectAreaWithFArea:@"北京市" withTarea:@"北京市" withFarea:3];
    
    UIImageView * image = (UIImageView*)[self.view viewWithTag:1000];
    image.transform = CGAffineTransformMakeRotation(M_PI_2);
    UIPickerView *education = [[UIPickerView alloc] init];
    ActionSheetPicker *actionSheet=[[ActionSheetPicker alloc]initWithTarget:self successAction:@selector(selectOK:) cancelAction:nil origin:education];
    
    CGRect pickerFrame = CGRectMake(0, 40, actionSheet.viewSize.width, 216);
    [education setFrame:pickerFrame];
    education.delegate = self;
    education.dataSource = self;
    //pickview  左选择按钮的文字
    UIButton *leftBtn =[UIButton buttonWithType:UIButtonTypeCustom];
    [leftBtn setTitle:@"取消"forState:UIControlStateNormal];
    leftBtn.frame=CGRectMake(0, 0, 50, 45);
    [leftBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    UIBarButtonItem *leftIte=[[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    //pickview    右选择按钮的文字
    UIButton *rightBtn =[UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setTitle:@"完成" forState:UIControlStateNormal];
    rightBtn.frame=CGRectMake(0, 0, 50, 45);
    [rightBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    UIBarButtonItem *rightIte=[[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    //将按钮添加到pickerview 上
    [actionSheet setDoneButton:rightIte];
    [actionSheet setCancelButton:leftIte];
    actionSheet.pickerView = education;
    actionSheet.title = @"地址选择";
    [actionSheet showActionSheetPicker];
    NSLog(@"点击的是地区选择");
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component

{
    NSInteger ss = [pickerView selectedRowInComponent:0];
    NSInteger dd = [pickerView selectedRowInComponent:1];
    
    switch (component) {
        case 0:
        {
            NSDictionary *dict = [_provienceArray objectAtIndex:row];
            NSString *code = MySetValue(dict, @"provinceName");
            if (code.length > 0)
            {
                _cityArray = [AREA selectAreaWithFArea:code withTarea:nil withFarea:2];
                [pickerView reloadComponent:1];
                dd = 0;
                NSDictionary *cityDict = [_cityArray objectAtIndex:dd];
                NSString * cityFcode = MySetValue(cityDict, @"cityName");
                if (cityFcode.length > 0)
                {
                    //                    _areaArray = [AREA selectAreaWithFArea:code withTarea:cityFcode withFarea:3];
                    //                    [pickerView reloadComponent:2];
                }
            }
        }
            break;
        case 1:
        {
            NSDictionary *dict = [_cityArray objectAtIndex:row];
            NSString *code = MySetValue(dict, @"cityName");
            
            NSDictionary * dics = [_provienceArray objectAtIndex:ss];
            NSString * str = MySetValue(dics, @"provinceName");
            NSLog(@"%@",code);
            
            NSLog(@"%@",str);
            if (code.length > 0) {
                //                _areaArray = [AREA selectAreaWithFArea:str withTarea:code withFarea:3];
                //                [pickerView reloadComponent:2];
            }
        }
            break;
        case 2:{
            
        }
            break;
            
        default:
            break;
    }
}


- (void)selectOK:(id)sender{
    
    UIPickerView *pick = sender;
    NSInteger row = [pick selectedRowInComponent:0];
    NSDictionary *dict = [_provienceArray objectAtIndex:row];
    NSString *provinceName = MySetValue(dict, @"provinceName");//省名称
    NSString *provinceCode = MySetValue(dict, @"provinceCode");//省编码
    
    NSInteger row1 = [pick selectedRowInComponent:1];
    NSDictionary *dict1 = [_cityArray objectAtIndex:row1];
    NSString *cityName = MySetValue(dict1, @"cityName");//市名称
    NSString *citycode = MySetValue(dict1, @"cityCode");//市编码
    
    //    NSInteger row2 = [pick selectedRowInComponent:2];
    //    NSDictionary *dict2 = [_areaArray objectAtIndex:row2];
    //    NSString *countyName = MySetValue(dict2, @"countyName");//县名称
    //    NSString * countycode = MySetValue(dict2, @"countyCode");//县编码
    
    [dic setObject:provinceCode forKey:@"provincecode"];//省编码
    [dic setObject:provinceName forKey:@"provincename"]; //省名称
    [dic setObject:citycode forKey:@"citycode"];//市编码
    [dic setObject:cityName forKey:@"cityname"]; //市名称
    //    [dic setObject:countycode forKey:@"countycode"];//县编码
    //    [dic setObject:countyName forKey:@"countyname"]; //县名称
    //    NSString * btnName = [NSString stringWithFormat:@"%@%@%@",provinceName,cityName,countyName];
    NSString *provinceName1 = [NSString stringWithFormat:@"%@",provinceName];
    NSString *cityName1 = [NSString stringWithFormat:@"%@",cityName];
    
    NSString * btnName = nil;
    if ([provinceName1 isEqualToString:cityName1]) {
        btnName = [NSString stringWithFormat:@"%@",provinceName1];
    }else{
        btnName = [NSString stringWithFormat:@"%@%@",provinceName1,cityName1];
    }
    
    [_AreaBtn setTitle:btnName forState:UIControlStateNormal];
    UIImageView * image = (UIImageView*)[self.view viewWithTag:1000];
    image.transform = CGAffineTransformMakeRotation(0);
}

//  跳出的pickerview  显示列数
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}

//显示pickerview 每个视图的行数
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component

{
    switch (component) {
        case 0:
            return _provienceArray.count;
            break;
        case 1:
            return _cityArray.count;
            break;
            //                case 2:
            //                    return _areaArray.count;
            //                    break;
        default:
            break;
    }
    return 0;
}

//显示每个pickerview  每行的具体内容
-(UIView*)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view

{
    UILabel *lable  = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 30)];
    lable.adjustsFontSizeToFitWidth = YES;
    lable.textAlignment = NSTextAlignmentCenter;
    
    switch (component) {
        case 0:{
            NSDictionary *dict = [_provienceArray objectAtIndex:row];
            lable.text = MySetValue(dict, @"provinceName");
        }
            break;
        case 1:{
            
            NSDictionary *dict = [_cityArray objectAtIndex:row];
            lable.text = MySetValue(dict, @"cityName");
        }
            break;
            
            //        case 2:{
            //
            //            NSDictionary *dict = [_areaArray objectAtIndex:row];
            //            lable.text = MySetValue(dict, @"countyName");
            //        }
            //            break;
        default:
            break;
    }
    return lable;
}

-(void)pressStoreBtn{
    
    __weak KeepAddressVC * weekself = self;
    weekself.store = YES;
    if (self.dataSouce[@"id"]) {
        NSLog(@"%@",self.dataSouce);
        [dic setObject:self.dataSouce[@"countyName"] forKey:@"countyname"];//详细地址
        [dic setObject:self.dataSouce[@"cityName"] forKey:@"cityname"];//详细地址
        [dic setObject:self.dataSouce[@"provinceName"] forKey:@"provincename"];//详细地址
        [dic setObject:self.dataSouce[@"provinceCode"] forKey:@"provincecode"];//省编码
        [dic setObject:self.dataSouce[@"cityCode"] forKey:@"citycode"];//市编码
    }
    
    
    NSString * phone = dic[@"phone"];
    NSString * contact = dic[@"contact"];
    NSString * address = dic[@"address"];
    NSString * unitname = dic[@"unitname"];
    NSString * area = [NSString stringWithFormat:@"%@%@%@",dic[@"provincename"],dic[@"countyname"],dic[@"cityname"]];
    
    NSMutableArray * arr = [[NSMutableArray alloc]init];
    [arr addObject:area];
    [arr addObject:unitname];
    [arr addObject:contact];
    [arr addObject:phone];
    [arr addObject:address];
    
    
    NSMutableArray * alertName = nil;
    if ([_addresstype isEqualToString:@"1"]) {
        alertName = @[@"您没有选择地址",
                      @"您没有填写收车单位",
                      @"您没有填写联系人",
                      @"您没有填写联系电话",
                      @"您没有填写详细地址"].mutableCopy;
    }
    else{
        alertName = @[@"您没有选择地址",
                      @"您没有填写发车单位",
                      @"您没有填写联系人",
                      @"您没有填写联系电话",
                      @"您没有填写详细地址"].mutableCopy;
    }
    
    for (int i = 0; i<5; i++) {
        NSString * string = arr[i];
        if (string.length == 0) {
            weekself.store = NO;
            [self createUIAlertController:alertName[i]];
            break;
        }
    }
    
    if (weekself.store) {
        if([Common validateUserPhone:phone]){
            hud = [WKProgressHUD popMessage:@"保存成功" inView:self.view duration:0.5 animated:YES];
            
            [Com afPostRequestWithUrlString:addressAdd_Url parms:dic finishedBlock:^(id responseObj) {
                
                NSMutableDictionary * dicObj =[NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableContainers error:nil];
                
                if (dicObj[@"success"]) {
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [hud dismiss:YES];
                        
                        
                        if (self.callBack) {
                            self.callBack(dic,self.addresstype);
                        }

                        [self.navigationController popViewControllerAnimated:YES];
                    });
                }else{
                    [self createUIAlertController:dicObj[@"message"]];
                }
            } failedBlock:^(NSString *errorMsg) {
            }];
        }else{
            [self createUIAlertController:@"您输入的手机号有误"];
        }
    }
}

-(void)createBackUIAlertController:(NSString*)title{
    UIAlertController * alert =[UIAlertController alertControllerWithTitle:@"提示" message:title preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * action =[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        for (UIViewController *controller in self.navigationController.viewControllers) {
            if ([controller isKindOfClass:[ChooseAddressVC class]]) {
                [self.navigationController popToViewController:controller animated:YES];
            }
        }
    }];
    UIAlertAction * action1 =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alert addAction:action1];
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
    
}

-(void)createUIAlertController:(NSString*)title

{
    UIAlertController * alert =[UIAlertController alertControllerWithTitle:@"提示" message:title preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * action =[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction * action1 =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alert addAction:action1];
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
}

-(UILabel*)createUIlabel:(NSString *)title andFont:(CGFloat)font andColor:(UIColor *)color{
    
    UILabel * label =[[UILabel alloc]init];
    label.text = title;
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = color;
    UIFont *fnt = [UIFont fontWithName:@"HelveticaNeue" size:font];CGSize size = [label.text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:fnt,NSFontAttributeName, nil]];
    CGFloat nameH = size.height;
    CGFloat nameW = size.width;
    label.textAlignment = NSTextAlignmentRight;
    label.frame =CGRectMake(0, 0, nameW, nameH);
    label.font = Font(font)
    return label;
}

-(UIButton*)createBtn:(NSString*)title andTag:(int)tag{
    
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:littleBlackColor forState:UIControlStateNormal];
    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    btn.tag = tag;
    return btn;
}

-(void)textFieldWithText:(UITextField *)textField{
    //500 501 502 503
    UITextField * field = (UITextField*)textField;
    switch (textField.tag) {
        case 500://发车单位/收车单位
            if ([self textField:field shouldChangeCharactersInRange:NSMakeRange(0, 0) replacementString:@""]) {
                [dic setObject:field.text forKey:@"unitname"]; //送达单位、收车单位
            }
            break;
        case 501: //联系人
            
            if ([self textField:field shouldChangeCharactersInRange:NSMakeRange(0, 0) replacementString:@""]) {
                [dic setObject:field.text forKey:@"contact"];
            }
            break;
        case 502://联系电话
            [dic setObject:field.text forKey:@"phone"];
            break;
        case 503://详细地址
            if ([self textField:field shouldChangeCharactersInRange:NSMakeRange(0, 0) replacementString:@""]) {
                [dic setObject:field.text forKey:@"address"];
            }
            break;
        default:
            break;
    }
}

-(UITextField*)createField:(NSString*)placeholder andTag:(int)tag andFont:(double)font{
    
    UITextField * field =[[UITextField alloc]init];
    field.frame = CGRectMake(0, 0, Main_Width-91, 50);
    field.delegate = self;
    field.userInteractionEnabled = YES;
    field.textAlignment = NSTextAlignmentLeft;
    field.keyboardType = UIKeyboardTypeDefault;
    //    field.returnKeyType = UIReturnKeySend;
    field.tag = tag;
    field.placeholder =placeholder;
    [field setFont:[UIFont fontWithName:@"STHeitiSC" size:font]];
    [field addTarget:self action:@selector(textFieldWithText:) forControlEvents:UIControlEventEditingChanged];
    return field;
}


//触摸方法
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{
    for (UITextField * field in self.view.subviews) {
        [field resignFirstResponder];
    }
}
//点击return按钮 键盘隐藏 这是协议中的方法
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    //键盘隐藏 也就是让键盘取消第一响应者身份
    [textField resignFirstResponder];
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
{  //string就是此时输入的那个字符textField就是此时正在输入的那个输入框返回YES就是可以改变输入框的值NO相反
    
    if ([string isEqualToString:@"\n"])  //按会车可以改变
    {
        return YES;
    }
    
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //得到输入框的内容
    
    if ([toBeString length] > kMaxLength) { //如果输入框内容大于20则弹出警告
        textField.text = [toBeString substringToIndex:kMaxLength];
        
        [self createUIAlertController:@"超过最大字数不能输入了"];
        return NO;
    }
    
    return YES;
}

@end
